package com.zzvcom.doc.paper;

import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.*;


import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * 尝试创建Word文档模板，创建一个包含标题、选择题、填空题、简答题的Word文档模板。
 * 演示
 */
public class CreateExamTemplate {

    public static void main(String[] args) throws Exception {
        // 创建文档包
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
        MainDocumentPart mainPart = wordMLPackage.getMainDocumentPart();

        // 确保样式部件存在
         wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart(true);
        // 添加自定义样式
        addCustomStyles(wordMLPackage);

        // 添加示例内容
        addSampleContent(mainPart);

        // 保存模板
        String outputPath = "doc/exam_template.docx";
        wordMLPackage.save(new File(outputPath));
        System.out.println("模板已生成：" + outputPath);
    }

    // 修改 addCustomStyles 方法，为样式添加完整格式
    private static void addCustomStyles(WordprocessingMLPackage wordMLPackage) throws Exception {
        Styles styles = wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getJaxbElement();

        // 1. Title 样式（大号字体，居中，加粗）
        Style titleStyle = createStyle("ExamTitle", "试卷标题", "paragraph", null);
        // 添加段落属性
        PPr titlePPr = new PPr();
        Jc titleJc = new Jc();
        titleJc.setVal(JcEnumeration.CENTER); // 居中对齐
        titlePPr.setJc(titleJc);
        titleStyle.setPPr(titlePPr);

        // 添加字符属性
        RPr titleRPr = new RPr();
        HpsMeasure titleSz = new HpsMeasure();
        titleSz.setVal(BigInteger.valueOf(28)); // 14号字体
        titleRPr.setSz(titleSz);
        BooleanDefaultTrue titleBold = new BooleanDefaultTrue();
        titleBold.setVal(true);
        titleRPr.setB(titleBold);
        titleStyle.setRPr(titleRPr);

        styles.getStyle().add(titleStyle);

        // 2. Question 样式（加粗）
        Style questionStyle = createStyle("ExamQuestion", "试卷题目", "paragraph", null);
        RPr questionRPr = new RPr();
        BooleanDefaultTrue questionBold = new BooleanDefaultTrue();
        questionBold.setVal(true);
        questionRPr.setB(questionBold);
        questionStyle.setRPr(questionRPr);
        styles.getStyle().add(questionStyle);

        // 3. Option 样式
        Style optionStyle = createStyle("ExamOption", "试卷选项", "paragraph", null);
        styles.getStyle().add(optionStyle);

        // 4. Answer 样式（绿色加粗）
        Style answerStyle = createStyle("ExamAnswer", "试卷答案", "paragraph", null);
        RPr answerRPr = new RPr();
        Color color = new Color();
        color.setVal("008000"); // 绿色
        answerRPr.setColor(color);
        BooleanDefaultTrue bold = new BooleanDefaultTrue();
        bold.setVal(true);
        answerRPr.setB(bold);
        answerStyle.setRPr(answerRPr);
        styles.getStyle().add(answerStyle);

        wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setJaxbElement(styles);
    }

    /**
     * 创建样式对象
     */
    private static Style createStyle(String styleId, String name, String  type, String basedOn) {
        Style style = new Style();
        style.setStyleId(styleId);
        Style.Name t = new Style.Name();
        t.setVal(name);
        style.setName(t);

        style.setType(type);

        if (basedOn != null) {
            Style.BasedOn basedOnObj = new Style.BasedOn();
            basedOnObj.setVal(basedOn);
            style.setBasedOn(basedOnObj);
        }

        // 设置显示优先级和格式标记，使样式在Word中可见
        Style.UiPriority uiPriority = new Style.UiPriority();
        uiPriority.setVal(new BigInteger("99"));
        style.setUiPriority(uiPriority);
        style.setQFormat(new BooleanDefaultTrue());
        return style;
    }

    /**
     * 添加示例试题内容
     */
    private static void addSampleContent(MainDocumentPart mainPart) throws Exception {
        ObjectFactory factory = new ObjectFactory();

        // 标题
        P titlePara = createParagraphWithStyle(factory, "2025年Java编程测试卷", "ExamTitle");
        mainPart.addObject(titlePara);

        // 空行
        mainPart.addObject(factory.createP());

        // 选择题
        P choiceTitle = createParagraphWithStyle(factory, "一、选择题", "ExamQuestion");
        mainPart.addObject(choiceTitle);

        // 第1题题干
        P question1 = createParagraphWithStyle(factory, "1. Java中，以下哪个类是所有类的父类？", "ExamQuestion");
        mainPart.addObject(question1);

        // 选项（自动编号）
        List<String> options1 = new ArrayList<>();
        options1.add("A. java.lang.Object.");
        options1.add("B. java.util.String");
        options1.add("C. java.io.Serializable");
        options1.add("D. java.lang.Class");
        for (String opt : options1) {
            mainPart.addObject(createParagraphWithStyle(factory, opt,"ExamOption"));
        }

        // 答案
        P answer1 = createParagraphWithStyle(factory, "答案：A", "ExamAnswer");
        mainPart.addObject(answer1);

        // 空行
        mainPart.addObject(factory.createP());
    }

    /**
     * 创建带样式的段落
     */
    private static P createParagraphWithStyle(ObjectFactory factory, String text, String styleId) {
        P para = factory.createP();

        PPr ppr = factory.createPPr();
        ppr.setPStyle(new PPrBase.PStyle());
        PPrBase.PStyle ps = ppr.getPStyle();
        ps.setVal(styleId);
        ppr.setPStyle(ps);
        para.setPPr(ppr);

        R run = factory.createR();
        Text t = factory.createText();
        t.setValue(text);
        run.getContent().add(t);
        para.getContent().add(run);

        return para;
    }


}
